const express = require('express')
const { queryDB, queryDBPromise } = require('../db/db.js')

const userRouter = express.Router()

/**
 * 注册
 */
userRouter.post('/register', (req, res) => {
	const username = req.body.username
	const password = req.body.password
	const age = req.body.age
	const sex = req.body.sex

	// 检查用户名是否已经注册
	const sql1 = `SELECT count(*) AS num FROM users WHERE username = '${username}'`
	
	queryDBPromise(sql1).then(data => {
		if (data[0].num > 0) {
			res.send({
				code: -1,
				message: '用户已经注册',
			})
		} else {
			// 保存到数据库
			const sql = `INSERT INTO users (username,password,age,sex)VALUES('${username}','${password}',${age},'${sex}')`
			queryDBPromise(sql).then(data => {
				res.send({
					code: 1,
					message: '注册用户成功!',
				})
			})
		}
	})
})

/**
 * 登录
 */
userRouter.post('/login', (req, res) => {
	const username = req.body.username
	const password = req.body.password

	const sql = `SELECT count(*) AS num FROM users WHERE username='${username}' AND password='${password}'`

	queryDBPromise(sql)
		.then(data => {
			if (data[0].num > 0) {
				res.send({
					code: 1,
					message: '登录成功!',
				})
			} else {
				res.send({
					code: -1,
					message: '用户名或密码出错!',
				})
			}
		})
		.catch(err => {
			console.log(err)
		})
})

module.exports = { userRouter }
